package com.sun;

/**
 * https://leetcode.cn/problems/remove-element/
 */
public class Test27移除元素 {
    public static void main(String[] args) {
        int[] nums = {0,1,2,2,3,0,4,2};
        int[] nums1 = {3,2,2,3};
        int[] nums2 = {2,2};
        int res = removeElement2(nums1, 3);
        System.out.println("res=" + res);
        for (int num : nums1) {
            System.out.println(num);
        }
    }

    /**
     * 方法一：自己
     */
    public static int removeElement1(int[] nums, int val) {
        int right = nums.length-1;
        int left = 0;
        while (left <= right){
            if (nums[left] == val){
                nums[left] = nums[right];
                right --;
            }else {
                left++;
            }
        }
        return  right + 1;
    }

    /**
     * 方法二：力扣官方，双指针
     */
    public static int removeElement2(int[] nums, int val) {
        int left = 0;
        for (int right = 0; right < nums.length; right++) {
            if (nums[right] != val){
                nums[left] = nums[right];
                left++;
            }
        }
        return left;
    }
}
